<template>
  <div class="container">
    <el-card class="search-card">
      <div class="search-form">
        <el-form :inline="true" class="form">
          <el-form-item label="合同号：">
            <el-select v-model="selectedContract" placeholder="请选择合同号" @change="handleContractChange" clearable
              filterable @keyup.enter="handleContractEnter" style="width: 260px">
              <el-option v-for="item in contractList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="识别码：">
            <el-select v-model="selectedPickingId" placeholder="请选择识别码" @change="handlePickingIdChange" clearable
              filterable @keyup.enter="handlePickingIdEnter" :disabled="!selectedContract" style="width: 260px">
              <el-option v-for="item in pickingIdList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryBillData"
              :disabled="!selectedContract || !selectedPickingId">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <template v-if="billData">
      <!-- 物料清单和品牌型号信息区域 -->
      <div class="main-content-area">
        <!-- 左侧：物料清单 -->
        <div class="left-panel" v-if="showMaterialsList">
          <el-card class="data-card full-height-card">
            <template #header>
              <div class="card-header">
                <div class="header-with-tabs">
                  <span>物料清单</span>
                  <el-checkbox v-model="includeSelftMade" @change="handleSelfMadeChange"
                    style="margin-left: 20px;">显示自制件</el-checkbox>
                </div>
              </div>
            </template>

            <!-- 物料基本信息显示 -->
            <el-row class="material-summary">
              <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                <div class="summary-item">
                  <div class="summary-label">物料总数量</div>
                  <div class="summary-value">{{ calculateTotalItemsCount() }}</div>
                </div>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                <div class="summary-item">
                  <div class="summary-label">未签物料</div>
                  <div class="summary-value">{{ calculateRemainingItemsCount() }}</div>
                </div>
              </el-col>
            </el-row>

            <el-table :data="displayItems" border style="width: 100%" :height="tableHeight" class="responsive-table"
              size="small">
              <!-- 汇总行 -->
              <el-table-column prop="item" label="物料编码" min-width="130">
                <template #header>
                  <div class="column-header">
                    <span>物料编码</span>
                    <div class="column-summary">共 {{ displayItems.length }} 种</div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="type" label="类型" width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.type === 'self_made' ? 'success' : 'info'">
                    {{ scope.row.type === 'self_made' ? '自制件' : '外购件' }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="qty" label="数量" min-width="80">
                <template #header>
                  <div class="column-header">
                    <span>数量</span>
                    <div class="column-summary">共 {{ calculateTotalQty() }} 件</div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="signed_qty" label="已签数量" min-width="80">
                <template #header>
                  <div class="column-header">
                    <span>已签数量</span>
                    <div class="column-summary">共 {{ calculateTotalSignedQty() }} 件</div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作" min-width="100" fixed="right">
                <template #default="scope">
                  <div style="display: flex; gap: 5px;">
                    <el-button type="primary" size="small" @click="selectItemForBrandModel(scope.row)" :disabled="scope.row.signed_qty >= scope.row.qty">
                      {{ scope.row.signed_qty >= scope.row.qty ? '完成' : '选择' }}
                    </el-button>
                    <el-button 
                      v-if="photoRequiredItems.includes(scope.row.item)"
                      type="warning" 
                      size="small" 
                      @click="handlePhotoClick(scope.row)"
                      class="compact-button">
                      {{ scope.row.photo_uploaded ? '已拍照' : '拍照' }}
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>

        <!-- 右侧：品牌型号信息 -->
        <div class="right-panel">
          <el-card class="data-card full-height-card">
            <template #header>
              <div class="card-header">
                <span>品牌型号信息</span>
                <div style="flex-grow: 1;"></div>
                <el-button type="success" @click="submitData" :disabled="shouldDisableSubmitButton" size="small">提交数据</el-button>
              </div>
            </template>
            <el-table :data="brandModelList" border style="width: 100%" v-loading="brandModelLoading"
              :height="tableHeight" class="responsive-table" size="small">
              <el-table-column prop="id" label="ID" min-width="30" show-overflow-tooltip />
              <el-table-column prop="item" label="物料编码" min-width="100" show-overflow-tooltip />
              <el-table-column prop="brand" label="品牌" min-width="70" show-overflow-tooltip />
              <el-table-column prop="model" label="型号" min-width="100" show-overflow-tooltip />
              <el-table-column prop="specification" label="规格" min-width="70" show-overflow-tooltip />
              <el-table-column prop="origin" label="产地" min-width="50" show-overflow-tooltip />
              <el-table-column prop="quantity" label="数量" min-width="60" />
              <el-table-column label="操作" width="60" fixed="right">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeBrandModel(scope.$index)"
                    class="compact-button">删除</el-button>
                </template>
              </el-table-column>
            </el-table>


          </el-card>
        </div>
      </div>
    </template>

    <!-- 添加/编辑品牌型号对话框 -->
    <el-dialog v-model="brandModelDialog.visible" :title="brandModelDialog.isEdit ? '编辑品牌型号' : '添加品牌型号'" width="50%">
      <el-form :model="brandModelForm" :rules="brandModelRules" ref="brandModelFormRef" label-width="80px">
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="brandModelForm.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="brandModelForm.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="brandModelForm.specification" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="brandModelForm.origin" placeholder="请输入产地" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="brandModelForm.quantity" :min="1" :max="9999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="brandModelDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitBrandModel">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 物料品牌型号选择对话框 -->
    <el-dialog v-model="materialBrandDialog.visible" title="选择物料品牌型号" width="70%">
      <template v-if="selectedItem">
        <div class="material-info">
          <el-alert title="物料信息" type="info" :closable="false">
            <div class="material-detail">
              <span><strong>物料编码：</strong>{{ selectedItem.item }}</span>
              <span><strong>数量：</strong>{{ selectedItem.qty }}</span>
              <span><strong>已签数量：</strong>{{ selectedItem.signed_qty }}</span>
            </div>
          </el-alert>
        </div>

        <el-table :data="availableBrandModels" border style="width: 100%; margin-top: 15px;"
          v-loading="brandModelLoading">
          <el-table-column prop="brand" label="品牌" width="160" />
          <el-table-column prop="model" label="型号" width="160" />
          <el-table-column prop="specification" label="规格" width="160" />
          <el-table-column prop="origin" label="产地" width="120" />
          <el-table-column label="数量" width="120">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" :min="1" :max="scope.row.maxQuantity" size="small" />
              <div class="max-quantity-hint">最大: {{ scope.row.maxQuantity }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button type="success" size="small" @click="addSingleBrandModel(scope.row)"
                class="compact-button">添加</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="dialog-footer" style="margin-top: 20px; text-align: right;">
          <el-button @click="materialBrandDialog.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 照片预览对话框 -->
    <el-dialog v-model="showPhotoPreview" title="照片预览" width="30%">
      <div class="photo-preview">
        <img :src="previewPhoto" alt="照片预览" style="max-width: 100%; max-height: 300px;">
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUploadPhoto">取消</el-button>
          <el-button type="primary" @click="confirmUploadPhoto" :loading="uploadLoading">确认保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 隐藏的拍照文件输入 -->
    <!-- 关键属性说明：
      type="file" - 这是一个文件选择输入
      accept="image/*" - 限制只接受图片文件
      capture="environment" - 这是最关键的属性，它会触发设备的相机应用
      在Android平板上，当用户点击拍照按钮时，会执行handleFileChange： -->
    <input
      ref="cameraInput"
      type="file"
      accept="image/*"
      capture="environment"
      @change="handleFileChange"
      style="display: none;"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onBeforeUnmount } from 'vue';
import type { Ref, ComputedRef } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import {
  getContracts, getPickingIds, getBillData, getBrandModel, submitBillData,
  getTempBrandModels, saveTempBrandModel, deleteTempBrandModels, deleteTempBrandModelById,
  getPhotoRequiredItems
} from '@/axios/api/item-brand';
import { useItemBrandStore } from '@/store/item-brand';
import useUserStore from '@/store/user';

// 类型定义
interface BillData {
  contract_no: string;
  picking_id?: string;
  work_order?: string;
  self_made_items: Array<{
    item: string;
    qty: number;
    signed_qty: number;
    [key: string]: any;
  }>;
  purchased_items: Array<{
    item: string;
    qty: number;
    signed_qty: number;
    [key: string]: any;
  }>;
  self_made_total_qty: number;
  self_made_remaining_qty: number;
  purchased_total_qty: number;
  purchased_remaining_qty: number;
  [key: string]: any;
}

interface BrandModel {
  id: number;
  brand: string;
  model: string;
  specification: string;
  origin: string;
  quantity: number;
  item?: string;
}

// 引入store
const itemBrandStore = useItemBrandStore();

// 表单数据
const selectedContract = ref<string>('');
const selectedPickingId = ref<string>('');
const billData = ref<BillData | null>(null);
const brandModelList = ref<BrandModel[]>([]);
const brandModelLoading = ref<boolean>(false);
const photoRequiredItems = ref<string[]>([]); // 存储需要拍照的物料编码列表

// 移除标签页变量，添加自制件勾选项
const includeSelftMade = ref<boolean>(false);
// 移除activeItemTab变量，不再需要
// const activeItemTab = ref<string>('self_made');
const showMaterialsList = ref<boolean>(true);
const selectedItem = ref<any>(null);
const availableBrandModels = ref<BrandModel[]>([]);

// 计算属性获取store中的数据
const contractList: ComputedRef<string[]> = computed(() => itemBrandStore.contractList);
const pickingIdList: ComputedRef<string[]> = computed(() => itemBrandStore.pickingIdList);

// 表单引用
const brandModelFormRef = ref<FormInstance | null>(null);

// 品牌型号表单对话框状态
const brandModelDialog = reactive({
  visible: false,
  isEdit: false,
  currentIndex: -1
});

// 物料品牌型号选择对话框状态
const materialBrandDialog = reactive({
  visible: false
});

// 品牌型号表单
const brandModelForm = reactive<BrandModel>({
  id:0,
  brand: '',
  model: '',
  specification: '',
  origin: '',
  quantity: 1
});

// 表单验证规则
const brandModelRules = {
  brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
  model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'change' }]
};

// 获取用户ID
//const userStore = useUserStore();

// 生命周期钩子
onMounted(async () => {
  await fetchContractList();
  calcTableHeight();
  window.addEventListener('resize', calcTableHeight);
});

// 组件销毁时移除事件监听
const beforeUnmount = () => {
  window.removeEventListener('resize', calcTableHeight);
};

// 计算表格高度
const tableHeight = ref<number>(400);
const calcTableHeight = () => {
  // 计算表格高度，留出一定空间给其他元素
  const windowHeight = window.innerHeight;
  tableHeight.value = windowHeight - 300; // 300是估计的其他元素高度总和
  // 设置最小高度
  if (tableHeight.value < 300) {
    tableHeight.value = 300;
  }
};

// 计算属性：显示的物料项
const displayItems = computed(() => {
  if (!billData.value) return [];

  // 总是包含外购件
  let items = [...billData.value.purchased_items].map(item => ({
    ...item,
    type: 'purchased'
  }));

  // 如果选择了显示自制件，则添加自制件到列表
  if (includeSelftMade.value) {
    const selfMadeItems = billData.value.self_made_items.map(item => ({
      ...item,
      type: 'self_made'
    }));
    items = [...items, ...selfMadeItems];
  }

  return items;
});

// 处理自制件勾选变化
const handleSelfMadeChange = () => {
  // 可以在这里添加额外逻辑，现在暂不需要
  console.log('显示自制件状态变更为:', includeSelftMade.value);
};

// 计算物料总数量
const calculateTotalItemsCount = () => {
  if (!billData.value) return 0;

  let total = billData.value.purchased_total_qty;
  if (includeSelftMade.value) {
    total += billData.value.self_made_total_qty;
  }

  return total;
};

// 计算未签物料数量
const calculateRemainingItemsCount = () => {
  if (!billData.value) return 0;

  let remaining = billData.value.purchased_remaining_qty;
  if (includeSelftMade.value) {
    remaining += billData.value.self_made_remaining_qty;
  }

  return remaining;
};

// 计算总数量 - 更新为使用displayItems
const calculateTotalQty = () => {
  if (!displayItems.value) return 0;
  return displayItems.value.reduce((sum, item) => sum + item.qty, 0);
};

// 计算总已签数量 - 更新为使用displayItems
const calculateTotalSignedQty = () => {
  if (!displayItems.value) return 0;
  return displayItems.value.reduce((sum, item) => sum + item.signed_qty, 0);
};

// 获取合同列表
const fetchContractList = async () => {
  try {
    const res = await getContracts();
    if (res.code === 200) {
      itemBrandStore.setContractList(res.data || []);
    }
  } catch (error) {
    console.error('获取合同列表失败:', error);
    ElMessage.error('获取合同列表失败');
  }
};

// 获取需要拍照的物料列表
const fetchPhotoRequiredItems = async (contractNo: string) => {
  try {
    const res = await getPhotoRequiredItems({ contract_no: contractNo });
    if (res.code === 200 && Array.isArray(res.data)) {
      photoRequiredItems.value = res.data;
      console.log('需要拍照的物料列表:', photoRequiredItems.value);
    }
  } catch (error) {
    console.error('获取需要拍照的物料列表失败:', error);
    ElMessage.error('获取需要拍照的物料列表失败');
  }
};

// 处理合同变更
const handleContractChange = async (value: string) => {
  // 清空识别码选择和签单数据
  selectedPickingId.value = '';
  itemBrandStore.setPickingIdList([]);
  billData.value = null;
  brandModelList.value = [];

  if (!value) {
    photoRequiredItems.value = []; // 清空拍照物料列表
    return;
  }

  itemBrandStore.setCurrentContract(value);
  
  // 获取需要拍照的物料列表
  await fetchPhotoRequiredItems(value);

  try {
    ElMessage.info('正在获取识别码列表...');
    const res = await getPickingIds({ contract_no: value });
    if (res.code === 200) {
      // 更新识别码下拉列表
      itemBrandStore.setPickingIdList(res.data || []);

      if (res.data && res.data.length > 0) {
        ElMessage.success(`已获取${res.data.length}条识别码数据`);
      } else {
        ElMessage.warning('未找到该合同号对应的识别码');
      }
    } else {
      ElMessage.error(res.message || '获取识别码列表失败');
    }
  } catch (error) {
    console.error('获取识别码列表失败:', error);
    ElMessage.error('获取识别码列表失败');
  }
};

// 处理识别码变更
const handlePickingIdChange = async (value: string) => {
  if (value) {
    itemBrandStore.setCurrentPickingId(value);

    // 清空当前的品牌型号列表
    brandModelList.value = [];

    // 尝试加载临时保存的品牌型号数据
    try {
      console.log('正在查询临时品牌型号数据，参数:', {
        contract_no: selectedContract.value,
        picking_id: value
      });

      const res = await getTempBrandModels({
        contract_no: selectedContract.value,
        picking_id: value
      });

      console.log('临时品牌型号数据查询结果:', res);

      if (res.code === 200 && res.data && res.data.length > 0) {
        // 转换数据格式
        brandModelList.value = res.data.map((item: any) => ({
          id: item.ID, // 保存临时ID以便后续更新或删除
          brand: item.Brand,
          model: item.Model,
          specification: item.Specification || '',
          origin: item.Origin || '',
          quantity: item.Quantity,
          item: item.MaterialCode,
          
        }));

        ElMessage.success(`已加载${brandModelList.value.length}条临时保存的品牌型号数据`);
      } else {
        console.log('未查询到临时品牌型号数据或数据为空');
      }

      // 自动触发查询
      if (selectedContract.value) {
        queryBillData();
      }
    } catch (error) {
      console.error('加载临时品牌型号数据失败:', error);
      ElMessage.error('加载临时品牌型号数据失败');
    }
  }
};

// 处理合同号回车事件
const handleContractEnter = () => {
  if (selectedContract.value && !selectedPickingId.value) {
    // 如果已输入合同号但还没有识别码，聚焦到识别码输入框
    // 暂不实现聚焦，因为需要引用DOM元素
  } else if (selectedContract.value && selectedPickingId.value) {
    // 如果已经有合同号和识别码，则触发查询
    queryBillData();
  }
};

// 处理识别码回车事件
const handlePickingIdEnter = () => {
  if (selectedContract.value && selectedPickingId.value) {
    queryBillData();
  }
};

// 查询签单数据
const queryBillData = async () => {
  if (!selectedContract.value || !selectedPickingId.value) {
    ElMessage.warning('请选择合同号和识别码');
    return;
  }

  try {
    const res = await getBillData({
      contract_no: selectedContract.value,
      picking_id: selectedPickingId.value
    });

    if (res.code === 200) {
      billData.value = res.data;
      itemBrandStore.setBillData(res.data);

      // 默认选择第一个物料项（现在是外购件）
      if (billData.value.purchased_items && billData.value.purchased_items.length > 0) {
        selectedItem.value = { ...billData.value.purchased_items[0], type: 'purchased' };
      } else if (includeSelftMade.value && billData.value.self_made_items &&
        billData.value.self_made_items.length > 0) {
        selectedItem.value = { ...billData.value.self_made_items[0], type: 'self_made' };
      }

      // 加载此识别码之前保存的临时数据
      try {
        const tempRes = await getTempBrandModels({
          contract_no: selectedContract.value,
          picking_id: selectedPickingId.value
        });

        if (tempRes.code === 200 && tempRes.data && tempRes.data.length > 0) {
          brandModelList.value = tempRes.data.map((item: any) => ({
            brand: item.Brand,
            model: item.Model,
            specification: item.Specification,
            origin: item.Origin,
            quantity: item.Quantity,
            item: item.MaterialCode,
            id: item.ID
          }));

          // 更新物料的已签数量
          updateSignedQuantities();

          ElMessage.success(`已加载${brandModelList.value.length}条临时保存的品牌型号数据`);
        }
      } catch (error) {
        console.error('加载临时品牌型号数据失败:', error);
      }
    }
  } catch (error) {
    console.error('查询签单数据失败:', error);
    ElMessage.error('查询签单数据失败');
  }
};

// 更新已签数量的辅助函数
const updateSignedQuantities = () => {
  if (!billData.value || brandModelList.value.length === 0) return;

  // 按物料编码分组统计数量
  const quantityByMaterial: { [key: string]: number } = {};

  brandModelList.value.forEach(model => {
    if (model.item) {
      quantityByMaterial[model.item] = (quantityByMaterial[model.item] || 0) + model.quantity;
    }
  });

  // 更新自制件的已签数量
  billData.value.self_made_items.forEach(item => {
    if (quantityByMaterial[item.item]) {
      item.signed_qty = quantityByMaterial[item.item];
    }
  });

  // 更新外购件的已签数量
  billData.value.purchased_items.forEach(item => {
    if (quantityByMaterial[item.item]) {
      item.signed_qty = quantityByMaterial[item.item];
    }
  });

  // 更新总体统计数量
  const selfMadeSignedTotal = billData.value.self_made_items.reduce((sum, item) => sum + item.signed_qty, 0);
  const purchasedSignedTotal = billData.value.purchased_items.reduce((sum, item) => sum + item.signed_qty, 0);

  billData.value.self_made_remaining_qty = billData.value.self_made_total_qty - selfMadeSignedTotal;
  billData.value.purchased_remaining_qty = billData.value.purchased_total_qty - purchasedSignedTotal;
};

// 选择物料编码，打开品牌型号选择对话框
const selectItemForBrandModel = async (item: any) => {
  if (!item || !item.item) {
    ElMessage.warning('物料信息不完整');
    return;
  }

  selectedItem.value = item;
  availableBrandModels.value = [];

  try {
    brandModelLoading.value = true;
    console.log('使用物料编码查询品牌型号:', item.item);

    const res = await getBrandModel({
      material_code: item.item
    });

    if (res.code === 200) {
      // 计算剩余可签数量
      const remainingQty = Math.max(1, item.qty - item.signed_qty); // 确保最小值为1

      // 设置每个品牌型号的默认数量和最大可选数量
      availableBrandModels.value = (res.data || []).map((model: any) => ({
        ...model,
        quantity: 1, // 默认数量为1
        item: item.item,
        maxQuantity: remainingQty
      }));

      // 打开选择对话框
      materialBrandDialog.visible = true;
    } else {
      ElMessage.warning('未找到该物料的品牌型号信息');
    }
  } catch (error) {
    console.error('获取品牌型号数据失败:', error);
    ElMessage.error('获取品牌型号数据失败');
  } finally {
    brandModelLoading.value = false;
  }
};

// 打开添加品牌对话框
const openAddBrandDialog = () => {
  brandModelDialog.visible = true;
  brandModelDialog.isEdit = false;
  brandModelDialog.currentIndex = -1;
  brandModelForm.brand = '';
  brandModelForm.model = '';
  brandModelForm.specification = '';
  brandModelForm.origin = '';
  brandModelForm.quantity = 1;
};

// 编辑品牌型号
const editBrandModel = (row: BrandModel) => {
  const index = brandModelList.value.findIndex((item: BrandModel) =>
    item.brand === row.brand && item.model === row.model);

  if (index !== -1) {
    brandModelDialog.visible = true;
    brandModelDialog.isEdit = true;
    brandModelDialog.currentIndex = index;

    brandModelForm.brand = row.brand;
    brandModelForm.model = row.model;
    brandModelForm.specification = row.specification;
    brandModelForm.origin = row.origin || '';
    brandModelForm.quantity = row.quantity;
  }
};

// 删除品牌型号
const removeBrandModel = async (index: number) => {
  ElMessageBox.confirm('确定要删除此品牌型号记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 获取要删除的品牌型号记录
    const model = brandModelList.value[index];
    const quantity = model.quantity;
    const itemCode = model.item;
    const tempId = model.id;
    // 如果有临时ID，则从数据库中删除
    if (tempId) {
      try {
        await deleteTempBrandModelById(tempId);
      } catch (error) {
        console.error('删除临时品牌型号数据失败:', error);
      }
    }

    // 删除记录
    brandModelList.value.splice(index, 1);

    // 更新已签数量
    if (itemCode) {
      // 查找物料编码对应的项
      const findItemInList = (items: any[]) => {
        return items.find(item => item.item === itemCode);
      };

      // 先在自制件列表中查找
      let itemToUpdate = findItemInList(billData.value.self_made_items);
      let isSelfMade = false;

      if (itemToUpdate) {
        isSelfMade = true;
        // 减少已签数量
        itemToUpdate.signed_qty -= quantity;
        // 确保已签数量不小于0
        itemToUpdate.signed_qty = Math.max(0, itemToUpdate.signed_qty);
        // 更新未签数量统计
        billData.value.self_made_remaining_qty += quantity;
      } else {
        // 如果不是自制件，在外购件列表中查找
        itemToUpdate = findItemInList(billData.value.purchased_items);
        if (itemToUpdate) {
          // 减少已签数量
          itemToUpdate.signed_qty -= quantity;
          // 确保已签数量不小于0
          itemToUpdate.signed_qty = Math.max(0, itemToUpdate.signed_qty);
          // 更新未签数量统计
          billData.value.purchased_remaining_qty += quantity;
        }
      }

      // 如果当前选中的物料与删除的相同，更新选中物料的已签数量
      if (selectedItem.value && selectedItem.value.item === itemCode) {
        selectedItem.value.signed_qty = itemToUpdate ? itemToUpdate.signed_qty : 0;
      }
    }

    ElMessage.success('删除成功');
  }).catch(() => { });
};

// 提交品牌型号表单
const submitBrandModel = async () => {
  if (!brandModelFormRef.value) return;

  brandModelFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const newBrandModel: BrandModel = {
        brand: brandModelForm.brand,
        model: brandModelForm.model,
        specification: brandModelForm.specification,
        origin: brandModelForm.origin,
        quantity: brandModelForm.quantity
      };

      if (brandModelDialog.isEdit) {
        // 编辑已有记录
        brandModelList.value[brandModelDialog.currentIndex] = newBrandModel;
        ElMessage.success('更新成功');
      } else {
        // 添加新记录
        brandModelList.value.push(newBrandModel);
        ElMessage.success('添加成功');
      }

      brandModelDialog.visible = false;
    } else {
      return false;
    }
  });
};

// 提交数据
const submitData = async () => {
  try {
    // 检查billData是否存在
    if (!billData.value) {
      ElMessage.warning('没有可用的签单数据，无法提交');
      return;
    }

    // 获取必要数据
    const contractNo = selectedContract.value || '';
    const pickingId = selectedPickingId.value || '';

    if (!contractNo || !pickingId) {
      ElMessage.warning('合同号或识别码无效，无法提交');
      return;
    }

    // 处理不需要签单的识别码情况（只有自制件且不需要签单）
    const hasSelfMadeOnly = billData.value.self_made_items.length > 0 && 
                            billData.value.purchased_items.length === 0;
    const noModelsSelected = brandModelList.value.length === 0;
    
    if (hasSelfMadeOnly && noModelsSelected && !includeSelftMade.value) {
      // 确认用户意图
      const confirmResult = await ElMessageBox.confirm(
        '当前识别码只有自制件且不需要签单，是否继续提交?',
        '确认提交',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => 'cancel');
      
      if (confirmResult === 'cancel') return;
      
      // 提交无需签单的识别码
      const res = await submitBillData({
        contract_no: contractNo,
        picking_id: pickingId,
        work_order: '',
        brand_models: [],
        skip_validation: true // 特殊标记，表示这是无需签单的情况
      });
      
      if (isSuccessResponse(res)) {
        ElMessage.success('提交成功');
        resetForm();
      } else {
        const errorMsg = getErrorMessage(res);
        ElMessage.error(errorMsg || '提交失败');
      }
      return;
    }
    
    // 处理需要签单的情况
    
    // 1. 验证签单数量
    // 检查已签单总数量与需求总数量是否一致
    let signedTotal = brandModelList.value.reduce((sum, item) => sum + item.quantity, 0);
    let requiredTotal = 0;

    // 安全获取self_made_total_qty和purchased_total_qty
    const selfMadeTotalQty = billData.value.self_made_total_qty || 0;
    const purchasedTotalQty = billData.value.purchased_total_qty || 0;

    if (includeSelftMade.value) {
      // 如果自制件签单已选中，需要检查自制件+外购件总数
      requiredTotal = selfMadeTotalQty + purchasedTotalQty;
      if (signedTotal !== requiredTotal) {
        ElMessage.warning(`已签单总数量(${signedTotal})与需求总数量(${requiredTotal})不符，不能提交`);
        return;
      }
    } else {
      // 否则只检查外购件
      requiredTotal = purchasedTotalQty;
      if (signedTotal !== requiredTotal) {
        ElMessage.warning(`已签单总数量(${signedTotal})与外购件需求总数量(${requiredTotal})不符，不能提交`);
        return;
      }
    }

    if (brandModelList.value.length === 0) {
      ElMessage.warning('没有添加任何品牌型号数据，无法提交');
      return;
    }

    // 检查数据库中是否已有此识别码的签单数据
    try {
      const checkRes = await checkSignDataExists(pickingId);
      if (checkRes.exists) {
        ElMessage.warning('数据库中已有此识别码的签单数据，不能重复提交');
        return;
      }
    } catch (error) {
      console.error('检查签单数据失败:', error);
    }

    // 构造提交数据
    const submitData = {
      contract_no: contractNo,
      picking_id: pickingId,
      work_order: '',
      brand_models: brandModelList.value.map(item => ({
        brand: item.brand,
        model: item.model,
        specification: item.specification || '',
        origin: item.origin || '',
        quantity: item.quantity,
        item: item.item
      }))
    };

    // 显示提交中状态
    ElMessage.info('正在提交数据，请稍候...');
    console.log('准备提交数据:', submitData);

    try {
      const res = await submitBillData(submitData);
      console.log('提交结果:', res);
      
      if (isSuccessResponse(res)) {
        // 提交成功，清理临时数据并重置
        try {
          await deleteTempBrandModels({
            contract_no: contractNo,
            picking_id: pickingId
          });
        } catch (tempError) {
          console.warn('删除临时数据失败，但不影响提交结果', tempError);
        }

        ElMessage.success('提交成功');
        resetForm();
      } else {
        // 提交失败，展示错误信息
        const errorMsg = getErrorMessage(res);
        ElMessage.error(errorMsg || '提交失败，请检查数据后重试或联系系统管理员');
      }
    } catch (apiError) {
      // 处理API调用异常
      const errorMsg = getErrorMessage(apiError);
      ElMessage.error(errorMsg || '提交数据过程中发生错误，请稍后重试');
    }
  } catch (error) {
    // 处理整体函数执行异常
    console.error('提交数据过程发生未预期的错误:', error);
    ElMessage.error('系统错误，请刷新页面后重试');
  }
};

// 判断响应是否成功的辅助函数
const isSuccessResponse = (res) => {
  if (!res) return false;
  
  if (res.success === true) {
    return true;
  } else if (res.code === 200) {
    if (res.data && typeof res.data === 'object') {
      return res.data.success === true || !('success' in res.data);
    }
    return true;
  }
  
  return false;
};

// 获取错误消息的辅助函数
const getErrorMessage = (response) => {
  let errorMsg = '';

  if (response) {
    if (response.data && typeof response.data === 'object') {
      errorMsg = response.data.message || response.data.msg || '';
    }

    if (!errorMsg && (response.message || response.msg)) {
      errorMsg = response.message || response.msg;
    }
  }

  return errorMsg || '操作失败';
};

// 从API获取签单数据是否存在的辅助函数
const checkSignDataExists = async (pickingId) => {
  try {
    // 此处调用检查签单数据是否存在的API
    const res = await fetch(`/item-brand/check-sign-data/${pickingId}`);
    return await res.json();
  } catch (error) {
    console.error('检查签单数据失败:', error);
    return { exists: false };
  }
};

// 重置表单
const resetForm = async () => {
  // 显示加载提示
  ElMessage.info('正在重置数据...');

  try {
    // 清空当前选择和数据
    selectedContract.value = '';
    selectedPickingId.value = '';
    billData.value = null;
    brandModelList.value = [];
    selectedItem.value = null;

    // 清空识别码下拉框数据
    itemBrandStore.setPickingIdList([]);

    // 重置store状态
    itemBrandStore.resetAll();

    // 设置复选框为未选中
    includeSelftMade.value = false;

    // 重新获取未签单的合同号
    await fetchContractList();

    ElMessage.success('重置完成，已重新获取合同数据');
  } catch (error) {
    console.error('重置表单失败:', error);
    ElMessage.error('重置失败');
  }
};

// 修改addSingleBrandModel方法，支持区分物料类型
const addSingleBrandModel = async (model: BrandModel) => {
  if (!model || !model.quantity || model.quantity <= 0) {
    ElMessage.warning('请输入有效的数量');
    return;
  }

  // 获取物料剩余可签数量
  const remainingQty = selectedItem.value.qty - selectedItem.value.signed_qty;

  // 检查数量是否超出剩余可签数量
  if (model.quantity > remainingQty) {
    ElMessage.warning(`添加数量(${model.quantity})超过物料剩余可签数量(${remainingQty})`);
    return;
  }

  // 检查是否已存在相同的品牌型号
  // const existingIndex = brandModelList.value.findIndex(
  //   item => item.brand === model.brand && 
  //           item.model === model.model && 
  //           item.specification === model.specification &&
  //           item.item === model.item
  // );

  try {
    ElMessage.info('正在保存数据...');


    // 构造新增参数
    const createParams = {
      contract_no: selectedContract.value,
      picking_id: selectedPickingId.value,
      material_code: selectedItem.value.item,
      brand: model.brand,
      model: model.model,
      specification: model.specification || '',
      origin: model.origin || '',
      quantity: model.quantity
    };

    // 添加新记录，并保存到临时存储
    const res = await saveTempBrandModel(createParams);
    console.log(res);
    // 确保返回的数据中包含ID
    if (res.code === 200 && res.data && res.data.ID) {
      brandModelList.value.push({
        id: res.data.ID,
        brand: model.brand,
        model: model.model,
        specification: model.specification || '',
        origin: model.origin || '',
        quantity: model.quantity,
        item: selectedItem.value.item,
      });
    } else {
      ElMessage.error('保存临时品牌型号数据失败');
      return;
    }
    // 更新物料的已签数量
    selectedItem.value.signed_qty += model.quantity;

    // 更新签单基本信息中的数量统计
    if (billData.value) {
      const itemType = selectedItem.value.type;
      if (itemType === 'self_made') {
        billData.value.self_made_remaining_qty -= model.quantity;
      } else {
        billData.value.purchased_remaining_qty -= model.quantity;
      }
    }

    // 更新物料数组中的已签数量
    updateItemSignedQuantity();

    // 重置该行的数量为1
    model.quantity = 1;

    ElMessage.success('添加成功');

    // 自动关闭对话框
    materialBrandDialog.visible = false;
  } catch (error) {
    console.error('添加品牌型号失败:', error);
    ElMessage.error('添加品牌型号失败');
  }
};

// 辅助函数：更新物料数组中的已签数量
const updateItemSignedQuantity = () => {
  if (!billData.value) return;

  // 根据物料编码和类型更新对应的物料项
  const itemType = selectedItem.value.type;
  const itemCode = selectedItem.value.item;

  if (itemType === 'self_made') {
    const itemIndex = billData.value.self_made_items.findIndex(item => item.item === itemCode);
    if (itemIndex !== -1) {
      billData.value.self_made_items[itemIndex].signed_qty = selectedItem.value.signed_qty;
    }
  } else {
    const itemIndex = billData.value.purchased_items.findIndex(item => item.item === itemCode);
    if (itemIndex !== -1) {
      billData.value.purchased_items[itemIndex].signed_qty = selectedItem.value.signed_qty;
    }
  }
};

// 添加计算属性判断是否应该禁用提交按钮
const shouldDisableSubmitButton = computed(() => {
  // 如果没有数据或合同号/识别码为空，禁用按钮
  if (!billData.value || !selectedContract.value || !selectedPickingId.value) {
    return true;
  }
  
  // 如果品牌型号列表不为空，允许提交
  if (brandModelList.value.length > 0) {
    return false;
  }
  
  // 特殊情况：只有自制件且不需要签单时，允许提交
  const hasSelfMadeOnly = billData.value.self_made_items && 
                          billData.value.self_made_items.length > 0 && 
                          billData.value.purchased_items && 
                          billData.value.purchased_items.length === 0;
  const notSigningSelfMade = !includeSelftMade.value;
  
  // 如果是只有自制件且不需要签单的情况，允许提交
  if (hasSelfMadeOnly && notSigningSelfMade) {
    return false;
  }
  
  // 其他情况禁用按钮
  return true;
});

// 添加照片相关变量
const cameraInput = ref<HTMLInputElement | null>(null);
const currentItem = ref<any>(null); // 当前需要拍照的物料
const previewPhoto = ref<string>('');
const showPhotoPreview = ref<boolean>(false);
const photoFile = ref<File | null>(null);
const uploadLoading = ref<boolean>(false);

// 处理拍照按钮点击
const handlePhotoClick = (row: any) => {
  // 设置当前拍照的物料
  currentItem.value = row;
  // 触发点击文件输入
  if (cameraInput.value) {
    cameraInput.value.click();// 这一行会触发系统相机
  }
};

// 处理文件选择改变
const handleFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files[0]) {
    // 存储选择的文件
    photoFile.value = target.files[0];
    
    // 创建预览URL
    previewPhoto.value = URL.createObjectURL(target.files[0]);
    
    // 显示预览对话框
    showPhotoPreview.value = true;
  }
  
  // 重置文件输入，以便下次选择同一文件时也能触发change事件
  if (cameraInput.value) {
    cameraInput.value.value = '';
  }
};

// 确认保存照片到本地
const confirmUploadPhoto = async () => {
  if (!photoFile.value || !currentItem.value) return;
  
  uploadLoading.value = true;
  try {
    // 生成文件名: 合同号_编码_时间戳.jpg
    const timestamp = new Date().getTime();
    const fileName = `${selectedContract.value}_${currentItem.value.item}_${timestamp}.jpg`;
    
    // 创建a标签用于下载
    const link = document.createElement('a');
    link.href = previewPhoto.value;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    
    // 触发点击下载
    link.click();
    
    // 清理
    document.body.removeChild(link);
    
    // 标记该物料已拍照
    if (currentItem.value) {
      currentItem.value.photo_uploaded = true;
    }
    
    // 更新物料列表显示
    const materialList = billData.value?.self_made_items.concat(billData.value?.purchased_items) || [];
    const item = materialList.find(item => item.item === currentItem.value?.item);
    if (item) {
      item.photo_uploaded = true;
    }
    
    ElMessage.success('照片已保存到本地');
    
    // 关闭预览对话框
    showPhotoPreview.value = false;
    // 清除预览和文件
    previewPhoto.value = '';
    photoFile.value = null;
  } catch (error) {
    console.error('保存照片出错:', error);
    ElMessage.error('保存照片出错');
  } finally {
    uploadLoading.value = false;
  }
};

// 取消上传照片
const cancelUploadPhoto = () => {
  // 关闭预览对话框
  showPhotoPreview.value = false;
  // 清除预览和文件
  previewPhoto.value = '';
  photoFile.value = null;
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-card,
.data-card {
  margin-bottom: 20px;
}

.form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-with-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-tabs {
  margin-bottom: -16px;
}

.actions-zone {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.material-info {
  margin-bottom: 15px;
}

.material-detail {
  display: flex;
  gap: 20px;
  margin-top: 5px;
}

.max-quantity-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 新的布局样式 */
.main-content-area {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-panel,
.right-panel {
  width: 49%;
  min-width: 320px;
}

.full-height-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

@media (max-width: 1200px) {
  .main-content-area {
    flex-direction: column;
  }

  .left-panel,
  .right-panel {
    width: 100%;
    min-width: 100%;
  }
}

.material-summary {
  margin-bottom: 15px;
  background-color: #f5f7fa;
  padding: 10px 5px;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 5px;
}

.summary-label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
  text-align: center;
  white-space: nowrap;
}

.summary-value {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  text-align: center;
  white-space: nowrap;
}

.overflow-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.column-header {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.column-summary {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
  white-space: nowrap;
}

.responsive-table {
  width: 100%;
  height: 100%;
  overflow: auto;
}

/* 确保表格自适应 */
:deep(.el-table__body),
:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  width: 100% !important;
}

:deep(.el-table .cell) {
  padding-left: 5px;
  padding-right: 5px;
}

/* 让操作列的按钮更紧凑 */
:deep(.el-button--small) {
  padding: 5px 10px;
}

/* 针对小屏幕的额外优化 */
@media (max-width: 768px) {
  .summary-label {
    font-size: 12px;
  }

  .summary-value {
    font-size: 13px;
  }

  :deep(.el-table .cell) {
    padding-left: 3px;
    padding-right: 3px;
  }
}

/* 紧凑型按钮 */
.compact-button {
  padding: 4px 8px;
  font-size: 12px;
}

:deep(.el-select-dropdown__item) {
  white-space: normal;
  word-break: break-all;
  height: auto;
  padding: 8px 20px;
}
</style>